package com.zllkj.mm.api.net;

import com.zllkj.mm.common.ClientConfig;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class HttpManager {

    public static final String BASE_URL = ClientConfig.BASE_URL;

    private volatile static HttpManager INSTANCE;

    private static final int DEFAULT_TIMEOUT = 6;

    private HttpService httpService;

    private HttpManager() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(genericClient())
                .build();
        httpService = retrofit.create(HttpService.class);
    }

    /**
     * 获取单例
     */
    public static HttpManager getInstance() {
        if (INSTANCE == null) {
            synchronized (HttpManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HttpManager();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 处理http请求
     *
     * @param basePar 封装的请求数据
     */
    public void doHttpDeal(BaseEntity basePar) {
        Observable observable = basePar.getObservable(httpService)
                /*失败后的retry配置*/
                .retryWhen(new RetryWhenNetworkException())
                /*生命周期管理*/
                //.compose(basePar.getRxAppCompatActivity().bindToLifecycle())
                /*http请求线程*/
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                /*回调线程*/
                .observeOn(AndroidSchedulers.mainThread())
                /*结果判断*/
                .map(basePar);
        /*数据回调*/
        observable.subscribe(basePar.getSubscirber());
    }

    public static OkHttpClient genericClient() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
//                    .addHeader("app_key", Constants.APP_KEY)
//                    .addHeader(StorageUtils.VER, StorageUtils.getString(StorageUtils.VER,MyApplication.getInstance()))
//                    .addHeader(StorageUtils.UUID,StorageUtils.getShareValue(MyApplication.getInstance(),StorageUtils.UUID))
//                    .addHeader(StorageUtils.PHONE,StorageUtils.getShareValue(MyApplication.getInstance(),StorageUtils.PHONE))
//                    .addHeader(StorageUtils.SYS,StorageUtils.getShareValue(MyApplication.getInstance(),StorageUtils.SYS))
                                .build();
                        return chain.proceed(request);
                    }
                })//添加请求头
                //  .addInterceptor(cacheInterceptor)       //添加本地缓存拦截器，用来拦截本地缓存
                //    .addNetworkInterceptor(cacheInterceptor)      //添加网络拦截器，用来拦截网络数据
                //添加缓存
                //  .cache(provideCache())
                .build();
        return httpClient;
    }

//    static Interceptor headInterceptor = ;


//    static Interceptor cacheInterceptor=new Interceptor() {
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            Request request = chain.request();
//            if(!isNetworkReachable(MyApplication.getInstance())){//如果网络不可用
//                request=request.newBuilder()
//                        .cacheControl(CacheControl.FORCE_CACHE)
//                        .build();
//
//            }else{//网络可用
//                request = request.newBuilder()
//                        .cacheControl(CacheControl.FORCE_NETWORK)
//                        .build();
//            }
//            Response response = chain.proceed(request);
//            if(isNetworkReachable(MyApplication.getInstance())){//如果网络可用
//                Log.d("OkHttp","网络可用响应拦截");
//                response= response.newBuilder()
//                        //覆盖服务器响应头的Cache-Control,用我们自己的,因为服务器响应回来的可能不支持缓存
//                        .header("Cache-Control", "public,max-age=2")
//                        .removeHeader("Pragma")
//                        .build();
//            }else{
//                Toast.makeText(MyApplication.getInstance(), "请检查网络连接是否可用！", Toast.LENGTH_SHORT).show();
////                    Log.d("OkHttp","网络不可用响应拦截");
////                    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
////                    response= response.newBuilder()
////                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
////                            .removeHeader("Pragma")
////                            .build();
//            }
//            return response;
//        }
//    };

    //设置缓存目录和缓存空间大小
//    private static Cache provideCache (){
//        Cache cache = null;
//        try {
//            cache = new Cache( new File( MyApplication.getInstance().getCacheDir(), "http-cache" ),
//                    20 * 1024 * 1024 ); // 20 MB
//        }catch (Exception e){
//            Log.e("cache","Could not create Cache!");
//        }
//        return cache;
//    }
}
